package com.webside.wap.index.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.webside.wap.listener.BaseData;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import com.webside.front.common.model.Bdictionary;
import com.webside.util.Common;
import com.webside.wap.common.model.BSeries;
import com.webside.wap.common.model.PBanner;
import com.webside.wap.common.service.BSeriesService;
import com.webside.wap.common.service.PBannerService;


@Controller
@SessionAttributes(types=PBanner.class)
@RequestMapping(value="/wap/")
public class IndexController {
	@Autowired
	PBannerService pBannerService;
	@Autowired
	BSeriesService bSeriesService;
	//
	private Configuration freemarker_cfg = null;
	
	/**
	 * 创建多级目录
	 * 
	 * @param path
	 *            String
	 * @return boolean 是否成功
	 */
	private boolean creatDirs(String path) {
		File aFile = new File(path);
		if (!aFile.exists()) {
			return aFile.mkdirs();
		} else {
			return true;
		}
	}

	/**
	 * 
	 * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.
	 * 
	 * @param templateFilePath
	 *            获取模板路径
	 * @return Configuration 返回freemaker的配置属性
	 * @throws Exception
	 */
	private Configuration getFreeMarkerCFG(String templateFilePath) throws Exception {
		if (null == this.freemarker_cfg) {

			this.freemarker_cfg = new Configuration();
			try {
				this.freemarker_cfg.setDirectoryForTemplateLoading(new File(templateFilePath));
			} catch (Exception ex) {
				throw ex;
			}
		}
		return this.freemarker_cfg;
	}

	/**
	 * 生成静态文件.
	 * 
	 * @param templateFileName
	 *            模板文件名,相对htmlskin路径,例如"/tpxw/view.ftl"
	 * @param propMap
	 *            用于处理模板的属性Object映射
	 * @param htmlFilePath
	 *            要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/"
	 * @param htmlFileName
	 *            要生成的文件名,例如 "1.htm"
	 * @param templateFilePath
	 *            模板路径
	 * @return boolean true代表生成文件成功
	 */
	public void geneHtmlFile(String templateFileName, Map propMap, String htmlFilePath, String htmlFileName,
			String templateFilePath) {

		try {
			Template t = this.getFreeMarkerCFG(templateFilePath).getTemplate(templateFileName);
			// 如果根路径存在,则递归创建子目录
			this.creatDirs(htmlFilePath);
			File afile = new File(htmlFilePath + "/" + htmlFileName);
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(afile), "UTF-8"));
			t.process(propMap, out);
			out.flush();
			out.close();
		} catch (TemplateException e) {
			System.out.print(e.getMessage());
		} catch (IOException e) {
			System.out.print(e.getMessage());
		} catch (Exception e) {
			System.out.print(e.getMessage());
		}
	}
	
	@RequestMapping("createIndexHtml.html")
	public String createIndexHtml(Model m, Bdictionary bdictionary, HttpServletRequest request) {
		this.staticCreat(request.getContextPath(),request);
		
		return Common.BACKGROUND_PATH + "/wap/test";
	}
	
	private void staticCreat(String basepath, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		
		/****************************首页轮播图部分*****************************/
		List<PBanner> pBanner = pBannerService.getAllByTarget("BANNER");
		
		map.put("pBanner", pBanner);
		System.out.println(pBanner);
		/****************************首页推送部分******************************/
		//精彩预告
		List<BSeries> moviePrevue = bSeriesService.selectIndexMovieByKind(new BSeries("MOVIE_PREVUE","PUBLISHED"));
		map.put("moviePrevue", moviePrevue);
		//卫视同步
		List<BSeries> tvplayStartv = bSeriesService.selectIndexMovieByKind(new BSeries("TVPLAY_STARTV","PUBLISHED"));
		map.put("tvplayStartv", tvplayStartv);
		//日韩热播
		List<BSeries> tvplayRihan = bSeriesService.selectIndexMovieByKind(new BSeries("TVPLAY_RIHAN","PUBLISHED"));
		map.put("tvplayRihan", tvplayRihan);
		//美剧精选
		List<BSeries> tvplayOumei = bSeriesService.selectIndexMovieByKind(new BSeries("TVPLAY_OUMEI","PUBLISHED"));
		map.put("tvplayOumei", tvplayOumei);
		System.out.println(tvplayOumei.size());
		//佳片有约
		List<BSeries> movieJiapian = bSeriesService.selectIndexMovieByKind(new BSeries("MOVIE_JIAPIAN","PUBLISHED"));
		map.put("movieJiapian", movieJiapian);
		//院线大片
		List<BSeries> movieYuanxian = bSeriesService.selectIndexMovieByKind(new BSeries("MOVIE_YUANXIAN","PUBLISHED"));
		map.put("movieYuanxian", movieYuanxian);
		//热血（动漫）剧场
		List<BSeries> cartoonHot = bSeriesService.selectIndexMovieByKind(new BSeries("CARTOON_HOT","PUBLISHED"));
		map.put("cartoonHot", cartoonHot);
		System.out.println(cartoonHot.size());
//		model.addAllAttributes(collection);
		map.put("baseImgPath",BaseData.img_base_path);
		map.put("basePath", basepath);
		this.geneHtmlFile("index.ftl", map, request.getSession().getServletContext().getRealPath("/wap/"), "index.html",
		request.getSession().getServletContext().getRealPath("/WEB-INF/ftl/"));
		System.out.println(request.getSession().getServletContext().getRealPath("/WEB-INF/view/f/")+"===============");
	}

	@RequestMapping(value="indexNotUse.html")
	public String selectAll(Model model){
//		/****************************首页轮播图部分*****************************/
//		List<PBanner> pBanner = pBannerService.getAllByTarget("BANNER");
//		model.addAttribute("pBanner", pBanner);
//		System.out.println(pBanner);
//		/****************************首页推送部分******************************/
//		//精彩预告
//		List<BSeries> moviePrevue = bSeriesService.selectIndexMovieByKind(new BSeries("MOVIE_PREVUE","PUBLISHED"));
//		model.addAttribute("moviePrevue", moviePrevue);
//		//卫视同步
//		List<BSeries> tvplayStartv = bSeriesService.selectIndexMovieByKind(new BSeries("TVPLAY_STARTV","PUBLISHED"));
//		model.addAttribute("tvplayStartv", tvplayStartv);
//		//日韩热播
//		List<BSeries> tvplayRihan = bSeriesService.selectIndexMovieByKind(new BSeries("TVPLAY_RIHAN","PUBLISHED"));
//		model.addAttribute("tvplayRihan", tvplayRihan);
//		//美剧精选
//		List<BSeries> tvplayOumei = bSeriesService.selectIndexMovieByKind(new BSeries("TVPLAY_OUMEI","PUBLISHED"));
//		model.addAttribute("tvplayOumei", tvplayOumei);
//		System.out.println(tvplayOumei.size());
//		//佳片有约
//		List<BSeries> movieJiapian = bSeriesService.selectIndexMovieByKind(new BSeries("MOVIE_JIAPIAN","PUBLISHED"));
//		model.addAttribute("movieJiapian", movieJiapian);
//		//院线大片
//		List<BSeries> movieYuanxian = bSeriesService.selectIndexMovieByKind(new BSeries("MOVIE_YUANXIAN","PUBLISHED"));
//		model.addAttribute("movieYuanxian", movieYuanxian);
//		//热血（动漫）剧场
//		List<BSeries> cartoonHot = bSeriesService.selectIndexMovieByKind(new BSeries("CARTOON_HOT","PUBLISHED"));
//		model.addAttribute("cartoonHot", cartoonHot);
//		System.out.println(cartoonHot.size());
////		model.addAllAttributes(collection);
//		model.addAttribute("baseImgPath",BaseData.img_base_path);
//		
		return Common.BACKGROUND_PATH + "/wap/index";
	}

}
